package com.omg.api.handle;

import java.util.Random;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.omg.api.argument.Argument;
import com.omg.api.argument.RegisterArgument;
import com.omg.api.result.Result;
import com.omg.api.result.body.RegisterBody;
import com.omg.api.result.header.RegisterHeader;
import com.omg.constant.ResponseCode;
import com.omg.persistence.dao.lifepoint.entity.LPUser;
import com.omg.persistence.delegate.lifepoint.LPUserDelegate;

/**
 * 
 * @author xiazhiquan
 * 
 *         May 29, 2011
 */
public class RegisterHandler extends Handler {

	private static final Logger LOG = Logger.getLogger(RegisterHandler.class
			.getName());

	private Random random = new Random();

	private static RegisterHandler instance = null;

	static {
		instance = new RegisterHandler();
	}

	public static RegisterHandler getInstance() {
		return instance;
	}

	public String handle(Argument argument) throws Exception {

		String email = ((RegisterArgument) argument).getEmail();
		String passwd = ((RegisterArgument) argument).getPasswd();
		String nickname = ((RegisterArgument) argument).getNickname();

		LPUser lpUser = LPUserDelegate.getInstance().getLPUserByEmail(email);
		if (lpUser != null) {
			throw new Exception("" + ResponseCode.AP_E_Info_EmailRegistered);
		}

		lpUser = LPUserDelegate.getInstance().getLPUserByNickname(nickname);
		if (lpUser != null) {
			throw new Exception("" + ResponseCode.AP_E_Info_NicknameOccupied);
		}

		lpUser = new LPUser();
		lpUser.setEmail(email);
		lpUser.setNickname(nickname);
		lpUser.setPasswd(passwd);

		lpUser.setUserid(getUserid());
		lpUser.setSid(getSid());

		return getJson(lpUser);
	}

	private final String getJson(LPUser lpUser) throws Exception {
		try {

			int ret = LPUserDelegate.getInstance().addLPUser(lpUser);

			if (ret != 0) {
				throw new Exception("" + ResponseCode.AP_E_Info_RegisterFailed);
			}

			// construct result
			Result result = new Result();

			// header
			RegisterHeader header = new RegisterHeader();
			header.setRespcode(ResponseCode.AP_E_Succ);
			result.setHeader(header);

			// body
			RegisterBody body = new RegisterBody();
			body.setSid(lpUser.getSid());
			result.setBody(body);

			return new Gson().toJson(result);
		} catch (Exception e) {
			e.printStackTrace();
			String errorMsg = e.getMessage();
			LOG.error(errorMsg, e);
			throw new Exception(""
					+ (errorMsg != null && !errorMsg.isEmpty() ? errorMsg
							: ResponseCode.AP_E_Info_UnkownError));
		}
	}

	private final String getUserid() {
		return this.getUniqString();
	}

	private final String getSid() {
		return this.getUniqString();
	}

	private final String getUniqString() {
		String hash1 = null;
		String hash2 = null;
		long r1 = 0;
		long r2 = 0;
		do {
			r1 = random.nextLong();
			r2 = random.nextLong();
			hash1 = Long.toHexString(r1);
			hash2 = Long.toHexString(r2);
		} while (hash1.length() != 16 || hash2.length() != 16);
		return hash1 + hash2;
	}

}
